import router, { NO_REDIRECT_WHITE_LIST } from "./index";
import { usePermissionStoreWithOut } from "@/store/modules/permission";
import { useUserStoreWithOut } from "@/store/modules/user";
import type { RouteRecordRaw } from "vue-router";
import type { UserInfo } from "@/api/user/types";

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
  if (userStore.getToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const userInfo = userStore.getUserInfo;
      if (!userInfo) {
        await userStore.getUserInfoByToken();
      }
      if (permissionStore.getIsAddRouters) {
        next();
        return;
      }
      const permissions =
        (userStore.getUserInfo as unknown as UserInfo).permissions ?? [];
      permissionStore.generateRoutes(permissions);
      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw);
      });
      // 更新根路由的redirect属性
      const rootRoute = router.getRoutes().find((r) => r.path === "/");
      if (rootRoute) {
        // 移除原有的根路由
        router.removeRoute(rootRoute.name!);
        // 添加更新后的根路由，包含新的redirect值
        const updatedRootRoute = permissionStore.getRouters.find(
          (r) => r.path === "/"
        );
        if (updatedRootRoute) {
          router.addRoute(updatedRootRoute as unknown as RouteRecordRaw);
        }
      }
      const redirectPath = from.query.redirect || to.path;
      const redirect = decodeURIComponent(redirectPath as string);
      const nextData =
        to.path === redirect ? { ...to, replace: true } : { path: redirect };
      permissionStore.setIsAddRouters(true);
      next(nextData);
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
